package jnpf.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.database.model.superQuery.ConditionJsonModel;
import jnpf.database.model.superQuery.SuperQueryJsonModel;
import jnpf.entity.DocumentVersionEntity;
import jnpf.mapper.DocumentVersionMapper;
import jnpf.model.documentversion.DocumentVersionForm;
import jnpf.model.documentversion.DocumentVersionPagination;
import jnpf.service.DocumentVersionService;
import jnpf.util.JsonUtil;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 * DocumentVersion
 * 版本： V3.2.0
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2023-12-20
 */
@Service
public class DocumentVersionServiceImpl extends ServiceImpl<DocumentVersionMapper, DocumentVersionEntity> implements DocumentVersionService  {


        @Autowired
        private UserProvider userProvider;






    @Override
    public List<DocumentVersionEntity> getList(DocumentVersionPagination documentVersionPagination){
        return getTypeList(documentVersionPagination,documentVersionPagination.getDataType());
    }
    @Override
    public List<DocumentVersionEntity> getTypeList(DocumentVersionPagination documentVersionPagination,String dataType){
        String userId=userProvider.get().getUserId();
        List<String> AllIdList =new ArrayList();
		List<List<String>> intersectionList =new ArrayList<>();
		int total=0;
		int documentVersionNum =0;
        QueryWrapper<DocumentVersionEntity> documentVersionQueryWrapper=new QueryWrapper<>();
//树形，异步父级查询条件
		List<String> allSuperIDlist = new ArrayList<>();
		String superOp ="";
	if (ObjectUtil.isNotEmpty(documentVersionPagination.getSuperQueryJson())){
		SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(documentVersionPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
		String matchLogic = superQueryJsonModel.getMatchLogic();
		List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
		for (ConditionJsonModel conditionjson : superQueryList){
            Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
            Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
            String tableName = configMap.get("relationTable")!=null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
		    if (map.get("multiple") != null) {
		        if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
		            conditionjson.setFieldValue("[]");
		        }
		    }
            conditionjson.setTableName(tableName);
		}
		List<String> allSuperList = new ArrayList<>();
		List<List<String>> intersectionSuperList  = new ArrayList<>();
        int documentVersionNum1 = 0;
        QueryWrapper<DocumentVersionEntity> documentVersionSuperWrapper = new QueryWrapper<>();
//        documentVersionNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(documentVersionSuperWrapper,superQueryList,matchLogic,"ext_document_version")
//        ,new DocumentVersionEntity(),documentVersionNum1);
//            if (documentVersionNum1>0){
//            List<String> documentVersionList =this.list(documentVersionSuperWrapper).stream().map(DocumentVersionEntity::getId).collect(Collectors.toList());
//            allSuperList.addAll(documentVersionList);
//            intersectionSuperList.add(documentVersionList);
//            }
//		superOp = matchLogic;
//		//and or
//		if(matchLogic.equalsIgnoreCase("and")){
//		    allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
//		}else{
//		    allSuperIDlist = allSuperList;
//		}
    }
    boolean pcPermission = false;
    boolean appPermission = false;
    boolean	isPc = true;

    if(isPc){
			if(ObjectUtil.isNotEmpty(documentVersionPagination.getDocid())){
                    documentVersionQueryWrapper.lambda().like(DocumentVersionEntity::getDocid,documentVersionPagination.getDocid());
             }
			if(ObjectUtil.isNotEmpty(documentVersionPagination.getMainurl())){
                    documentVersionQueryWrapper.lambda().like(DocumentVersionEntity::getMainurl,documentVersionPagination.getMainurl());
            }

			if(ObjectUtil.isNotEmpty(documentVersionPagination.getVersion())){
                    documentVersionQueryWrapper.lambda().like(DocumentVersionEntity::getVersion,documentVersionPagination.getVersion());
            }

			if(ObjectUtil.isNotEmpty(documentVersionPagination.getCopyurl())){
                    documentVersionQueryWrapper.lambda().like(DocumentVersionEntity::getCopyurl,documentVersionPagination.getCopyurl());
             }

			if(ObjectUtil.isNotEmpty(documentVersionPagination.getEnabledmark())){
                    documentVersionQueryWrapper.lambda().like(DocumentVersionEntity::getEnabledmark,documentVersionPagination.getEnabledmark());
            }

        }


        //排序

        if(StringUtil.isEmpty(documentVersionPagination.getSidx())){
            documentVersionQueryWrapper.lambda().orderByDesc(DocumentVersionEntity::getVersion);
        }else{
            try {
            	String sidx = documentVersionPagination.getSidx();
                String[] strs= sidx.split("_name");
                DocumentVersionEntity documentVersionEntity = new DocumentVersionEntity();
                Field declaredField = documentVersionEntity.getClass().getDeclaredField(strs[0]);
				declaredField.setAccessible(true);
				String value = declaredField.getAnnotation(TableField.class).value();
                 documentVersionQueryWrapper="asc".equals(documentVersionPagination.getSort().toLowerCase())?documentVersionQueryWrapper.orderByAsc(value):documentVersionQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        if("0".equals(dataType)){
            if((total>0 && AllIdList.size()>0) || total==0){
                Page<DocumentVersionEntity> page=new Page<>(documentVersionPagination.getCurrentPage(), documentVersionPagination.getPageSize());
                IPage<DocumentVersionEntity> userIPage=this.page(page, documentVersionQueryWrapper);
                return documentVersionPagination.setData(userIPage.getRecords(),userIPage.getTotal());
            }else{
                List<DocumentVersionEntity> list = new ArrayList();
                return documentVersionPagination.setData(list, list.size());
            }
        }else{
            return this.list(documentVersionQueryWrapper);
        }
    }

    @Override
    public DocumentVersionEntity getInfo(String id){
        QueryWrapper<DocumentVersionEntity> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(DocumentVersionEntity::getId,id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(DocumentVersionEntity entity){
        this.save(entity);
    }

    @Override
    public boolean update(String id, DocumentVersionEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(DocumentVersionEntity entity){
        if(entity!=null){
            this.removeById(entity.getId());
        }
    }
    //子表方法

    //列表子表数据方法



    //验证表单唯一字段
    @Override
    public String checkForm(DocumentVersionForm form,int i) {
        int total = 0;
		boolean isUp =StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
		String id="";
		String countRecover = "";
		if (isUp){
			 id = form.getId();
		}

        return countRecover;
    }

}
